﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using FPPrinter.Models.Doc;
using FPPrinter.utiles;
using PdfiumViewer;

namespace FPPrinter.Models.SourceFiles
{
    public class SourceFile : ISourceFile
    {
        string _rootfolderImage;
        public SourceFile(string pdfFilePath  , string rootfolder="")
        {
            _rootfolderImage = rootfolder;
            Name = Path.GetFileName(pdfFilePath);
            Url = pdfFilePath;
        }


        public string Name { get; set; }
        public string Url { get; set; }
        
        
        Random _r=new Random();
        public void Analysis()
        {
            _PagesImages = new List<IImage>();
            // (int w, int h) a4pix = (793, 1122);
            var dpi = 96;
            // var dpi = 296;
            var scaleup = 2.0;
            // Path to your PDF file 

            using (PdfDocument pdfDocument = PdfDocument.Load(Url))
            {
                ($"【{Name}】 没有内容").Required( pdfDocument.PageCount>0)  ;
                for (int pageNumber = 0; pageNumber < pdfDocument.PageCount; pageNumber++)
                {
                    
                    var ps = pdfDocument.PageSizes[pageNumber];
                    using (var pageImage = pdfDocument.Render(pageNumber, (int)(ps.Width * scaleup),
                               (int)(ps.Height * scaleup), dpi, dpi,
                               PdfRenderFlags.Annotations))
                    {
                        var rr = string.IsNullOrEmpty(_rootfolderImage) ? "" : $"{_rootfolderImage}";
                        var imgname = $"{rr }a_{Name}_{pageNumber + 1: 00}_{ _r.Next(1000) : 0000}.png";
                        
                        imgname.MakeSurePathIsAvaliable();
                        try
                        {
                            pageImage.Save(imgname, ImageFormat.Png);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }

                        //create the image for it
                        IImage img = new FPImage(imgname);

                        //put the image into the ISourceFile
                        this._PagesImages.Add(img);
                    }
                }
                
                HasAnalied = true;
            
                var firsPagesize = pdfDocument.PageSizes[0];
                var isLong = firsPagesize.Height/ firsPagesize.Width > 1.1  ; // h is 10% longer
                FileType=isLong?FileType.Long:FileType.Short;
            }

            
        }
        
        

        IList<IImage> _PagesImages { get; set; } = new List<IImage>();
        public IEnumerable<IImage> PagesImages { get=> _PagesImages;   }
        public bool HasAnalied { get; private set; }
        public FileType FileType { get; private set; }
    }
}